<template>
  <zx-container>
    <template #zx-primary-search>
      <zx-search-form
        v-model:formData="searchParams"
        :formItems="formItems"
        :resetFormData="resetFormData"
        v-model:page="pages.page"
        @search="searchTable"
      />
    </template>
    <template #zx-primary-header>
      <TableTitle title="投放站点管理列表">
        <template #after-title>
          <TableSelectTip :num="selectList.length" :clearFn="clearSelect" />
        </template>
        <div>
          <!-- 校验当前所在公司是否可见【投放站点续费申请】； -->
          <el-button
            v-if="allApplyTypeCodes.includes('domain_renewal')"
            type="primary"
            icon="Money"
            @click="renew"
          >
            批量续费
          </el-button>
          <el-button
            type="primary"
            icon="Download"
            :loading="exportLoading"
            @click="exportData"
          >
            导出
            <span v-if="exportLoading">（{{ exportProgress }}%）</span>
          </el-button>
        </div>
      </TableTitle>
    </template>
    <template #zx-primary-container>
      <zx-table
        ref="tableRef"
        height="100%"
        row-key="id"
        :loading="loading"
        :columns="columns"
        :data="tableData"
        minWidth="150"
        @selection-change="handleSelectionChange"
      >
        <!-- 若【到期时间】-【当日时间】小于或等于30天，则标红处理； -->
        <template #expiration_time="{ row }">
          <span :class="{ 'danger-text': row.is_due_soon == 1 }">
            {{ FORMAT_DATE(row.expiration_time) }}
          </span>
        </template>
      </zx-table>
      <zx-pagination
        v-model:page="pages.page"
        v-model:size="pages.per_page"
        :total="total"
        @change="getTableData"
      />
    </template>
  </zx-container>
  <GiveupDialog
    :activeRow="activeRow"
    v-model:show="showGiveupDialog"
    @reload="getTableData"
  />
  <RenewDialog
    v-model:show="showRenewDialog"
    :selectList="selectList"
    :type="applyCodesObj?.domain_renewal?.id"
    @success="afterSuccess"
  />
  <DetailDialog
    :activeRow="activeRow"
    :canEdit="$auth.hasPermi('resources:sites:edit')"
    v-model:show="showDetailDialog"
    @openEdit="openEdit"
  />
  <EditDialog
    v-model:show="showEditDialog"
    :activeRow="activeRow"
    @success="getTableData"
  />
</template>

<script setup>
import { useTable } from 'zhixin-ui';
import {
  companyResourceDomainList,
  companyResourceDomainExport
} from '@/api/resources.js';
import {
  companyBusinessGroupAll,
  companyDomainUsageAll,
  companySiteTypeAll,
  companyApplication_typeAll
} from '@/api/system';
import {
  formItems,
  columns,
  searchParams,
  selectList,
  injectData,
  resetFormData
} from './tableConst';
import TableTitle from '@/components/TableTitle';
import DetailDialog from './DetailDialog';
import GiveupDialog from './GiveupDialog';
import { PAGES, INIT_ORANIZE_PARAMS, FORMAT_DATE } from '@/utils/const';
import { exportExcel, handleSelectionSomeGroup } from '@/utils';
import TableSelectTip from '@/components/TableSelectTip';
import RenewDialog from './RenewDialog';
import EditDialog from './EditDialog';

const props = defineProps({
  activeOranize: {
    type: Object,
    default: () => {}
  }
});

// 表格hooks
const tableRef = ref();
const { loading, tableData, pages, total, getTableData } = useTable(
  companyResourceDomainList,
  {
    tableRef,
    searchParams,
    formItems,
    autorun: false,
    pages: PAGES()
  }
);

function initSearchParams() {
  pages.value.page = 1;
  INIT_ORANIZE_PARAMS(searchParams, props.activeOranize);
}
function searchTable(type) {
  if (type === 'reset') initSearchParams();
  getTableData();
}
function initTable(keep) {
  if (!keep) initSearchParams();
  getTableData();
}

// 选择 只能选择同一个团队
function handleSelectionChange(list) {
  handleSelectionSomeGroup({
    list,
    selectList,
    tableRef,
    flagCallBack(item, firstInfo) {
      return item.group?.id === firstInfo.group?.id;
    }
  });
}
function clearSelect() {
  tableRef.value?.zxTableRef?.clearSelection?.();
}

function afterSuccess() {
  clearSelect();
  getTableData();
}

// 导出
// 以【.xlsx】excel文档格式导出；
// 文档命名：站点资源-【时间戳】
const exportLoading = ref(false);
const exportProgress = ref(0);
function exportData() {
  exportExcel({
    loading: exportLoading,
    api: companyResourceDomainExport,
    params: searchParams,
    formItems,
    progress: exportProgress
  });
}

// 续费
const showRenewDialog = ref(false);
function renew() {
  if (!selectList.value.length) {
    return $msg.warning('请先选择续费域名');
  }
  showRenewDialog.value = true;
}

// 详情
const showDetailDialog = ref(false);
// 详情点击事件
const activeRow = ref({});
function handleDetail(row) {
  activeRow.value = row;
  showDetailDialog.value = true;
}

// 编辑
const showEditDialog = ref(false);
function openEdit(row) {
  activeRow.value = row;
  showDetailDialog.value = false;
  showEditDialog.value = true;
}

// 弃用
const showGiveupDialog = ref(false);
function giveUp(row) {
  activeRow.value = row;
  showGiveupDialog.value = true;
}

// 获取所有查询下拉
const allApplyTypeCodes = ref([]);
const applyCodesObj = ref({});
function getOptions() {
  // 申请类型 获取code
  companyApplication_typeAll().then(res => {
    const resData = res.data || [];
    allApplyTypeCodes.value = [];
    applyCodesObj.value = {};
    for (let i = resData.length - 1; i >= 0; i--) {
      const item = resData[i];
      if (!item.childs?.length) resData.splice(i, 1);
      item.childs?.forEach(it => {
        allApplyTypeCodes.value.push(it.code);
        applyCodesObj.value[it.code] = it;
      });
    }
  });
  // 业务组
  companyBusinessGroupAll().then(res => {
    const resData = res.data || [];
    formItems.business_group_id.options = [
      { label: '全部', value: undefined },
      ...resData.map(item => {
        return { label: item.name, value: item.id };
      })
    ];
  });
  // 域名用途
  companyDomainUsageAll().then(res => {
    const resData = res.data || [];
    for (let i = resData.length - 1; i >= 0; i--) {
      const item = resData[i];
      if (!item.childs?.length) resData.splice(i, 1);
    }
    formItems.domain_usage_map.options = [
      { name: '全部', id: '-1' },
      ...resData
    ];
  });
  // 站点类型 可能数据结构有变化
  companySiteTypeAll({ type: 'site_type' }).then(res => {
    const resData = res.data || [];
    formItems.site_type.options = [
      { label: '全部', value: undefined },
      ...resData.map(item => {
        return { label: item.name, value: item.id };
      })
    ];
  });
}

defineExpose({ initTable, getOptions });
injectData({ handleDetail, giveUp });
</script>

<style lang="scss" scoped></style>
